<template>
    <div style="display: flex; flex-direction: column; align-items: center;">
        <el-button type="primary" @click="handelClick" >选择班级</el-button>
        <div>已选中{{ multipleSelection.length || 0 }}个班级</div>
    </div>
    <CurrencyDialog
        v-model="visible"
        title="班级选择"
        size="large"
        @cancel="cancel"
        @confirm="handleConfirm"
    >
        <div style="padding: 10px 20px;">
            <CurrencyInput
                v-model="inpVal"
                style="width: 240px; margin-bottom: 20px;"
                placeholder="班级名称"
                @change="inpChange"
            ></CurrencyInput>
            <el-table
                ref="multipleTableRef"
                :data="tableData"
                class="table"
                style="width: 100%; height: 400px;"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column property="name" label="班级名称"/>
                <el-table-column property="gradeName" label="所属年级"/>
                <el-table-column property="headmasterName" label="班主任" />
            </el-table>
        </div>
    </CurrencyDialog>
</template>

<script lang="ts" setup>
import { h, ref, reactive, watch, computed, nextTick } from 'vue'
import { aesEncrypt, createRef, refs } from 'dsrz/utils'
import {
  ElMessage,
} from 'element-plus'
import type { FormInstance, TableInstance } from 'element-plus'

// 定义班级表格数据类型
interface ClassTableData {
  id: number
  name: string
  gradeName: string
  headmasterName: string
  [key: string]: any  // 允许其他任意字段
}

interface User {
  id: number
  date: string
  name: string
  address: string
}

const props = defineProps({
    formDetailsData: {
        type: Object,
        default: () => ({})
    }
})

// 定义 emits
const emit = defineEmits(['change'])

const visible = ref<boolean>(false)
const inpVal = ref('')
const tableData = ref<ClassTableData[]>([])

// 保存上一次确认的选中状态
const confirmedSelection = ref<ClassTableData[]>([])

const cancel = () => {
    // 取消时恢复为上一次确认的状态
    multipleSelection.value = JSON.parse(JSON.stringify(confirmedSelection.value))
    
    // 同步恢复表格的选中状态
    nextTick(() => {
        if (multipleTableRef.value) {
            // 先清空所有选中
            multipleTableRef.value.clearSelection()
            // 恢复上一次确认的选中
            confirmedSelection.value.forEach(row => {
                const matchRow = tableData.value.find(item => item.id === row.id)
                if (matchRow) {
                    multipleTableRef.value!.toggleRowSelection(matchRow, true)
                }
            })
        }
    })
    
    visible.value = false
}

const handleConfirm = () => {
    console.log('== 确认选中的班级 ', multipleSelection.value)
    // 保存当前选中状态为已确认状态
    confirmedSelection.value = JSON.parse(JSON.stringify(multipleSelection.value))
    // 向父组件发送选中的班级数据
    emit('change', multipleSelection.value)
    visible.value = false
}

const inpChange = async(val: string) => {
    console.log('== val inp ', val)
    // tableData.value = await getTableData({
    //     id: props.formDetailsData.id,
    //     name: val
    // })
}

const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<ClassTableData[]>([])
const handleSelectionChange = (val: ClassTableData[]) => {
    multipleSelection.value = val
}

const handelClick = () => {
    console.log('== 选中的年级ID ', props.formDetailsData)
    if (!props.formDetailsData?.id) {
        return ElMessage.warning('请选择年级')
    }
    visible.value = true

    // 打开弹窗时，恢复上一次确认的选中状态
    nextTick(() => {
        if (multipleTableRef.value) {
            // 先清空所有选中
            multipleTableRef.value.clearSelection()
            // 恢复上一次确认的选中状态
            confirmedSelection.value.forEach(confirmedItem => {
                const matchRow = tableData.value.find(row => row.id === confirmedItem.id)
                if (matchRow) {
                    multipleTableRef.value!.toggleRowSelection(matchRow, true)
                }
            })
        }
    })
}

// 监听年级ID变化，重新获取班级数据（只监听年级ID，不监听整个对象）
watch(() => props.formDetailsData?.id, (newGradeId, oldGradeId) => {
    console.log('== 年级ID变化 ', newGradeId, oldGradeId)
    // 只有年级ID真正变化时才重新获取数据和清空选中状态
    if (newGradeId !== oldGradeId) {
        if (newGradeId) {
            // 重新获取班级列表
            // tableData.value = await getTableData({
            //     gradeId: newGradeId,
            //     name: inpVal.value
            // })
            tableData.value = [
                { name: '男女中职1', gradeName: '2026级', id: 1, headmasterName: '班主任1' },
                { name: '男女中职2', gradeName: '2026级', id: 2, headmasterName: '班主任1' },
                { name: '男女中职3', gradeName: '2026级', id: 3, headmasterName: '班主任1' },
            ]
            // 年级变化时清空所有选中状态（包括已确认的）
            multipleSelection.value = []
            confirmedSelection.value = []
        } else {
            // 清空班级列表和选中状态
            tableData.value = []
            multipleSelection.value = []
            confirmedSelection.value = []
        }
    }
}, { immediate: true })

</script>